package com.mera.tektronix.csviewer.services

import org.apache.commons.logging.LogFactory
import org.springframework.context.MessageSource

import com.mera.tektronix.csviewer.common.api.*
import com.mera.tektronix.csviewer.common.dto.*
import com.mera.tektronix.csviewer.common.exception.LogicException
import com.mera.tektronix.csviewer.domain.*
import com.mera.tektronix.csviewer.transformers.ITransformer

class ProjectRemoteService implements IProjectService {
	static transactional = true
	private static final log = LogFactory.getLog(ProjectRemoteService.class)
	
	ITransformer projectTransformer
	MessageSource messageSource
	
	@Override
	public List<ProjectDto> getList() {
		List<Project> projects = Project.list(sort: "id", order: "asc");
		return projectTransformer.transformDomainToDtoList(projects);
	}

	@Override
	public List<ProjectDto> getListByDepartmentId(Long departmentId) {
		Department depTo = Department.get(departmentId);
		List<Project> projects = Project.findAllByDepartmentLike(depTo).sort({ a, b -> a.id <=> b.id } as Comparator);
		return projectTransformer.transformDomainToDtoList(projects);
	}
	
	@Override
	public ProjectDto getProjectById(Long id) {
		Project prj = Project.get(id);
		return projectTransformer.transformDomainToDto(prj);
	}

	@Override
	public void addProject(ProjectDto project) throws LogicException {
		Project prj = projectTransformer.transformDtoToDomain(project);
		
		if(!prj.save()) {
			def err = prj.errors.allErrors.collect {[
						  errorMessage : messageSource.getMessage(it, null)
					  ]}
			
			throw new LogicException(err);
		}

	}

	@Override
	public void deleteProject(Long id) {
		Project prj = Project.get(id);
		prj.delete(flush : true);
	}

}
